package com.wl.filter;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * zuul做登录自定义过滤器
 */
@Component
public class LoginFilter extends ZuulFilter {
    // filter类型，可以通过父类查看返回值信息示例，例如：pre、post
    @Override
    public String filterType() {
        return "pre";
    }
    // filter的执行顺序，数字越小，执行时机越高
    @Override
    public int filterOrder() {
        return 0;
    }
    // 是否执行run方法，true：执行/false：不执行
    @Override
    public boolean shouldFilter() {
        //1.获取请求地址
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String url = request.getRequestURI();
        //判断请求地址是否以login或者register结尾的
        if (url.endsWith("login")||url.endsWith("register")){
            return false;
        }
        return true;
    }

    @SneakyThrows
    @Override
    public Object run() throws ZuulException {
        //获取请求信息
        RequestContext currentContext = RequestContext.getCurrentContext();
        String token = currentContext.getRequest().getHeader("token");
        //设置请求字符集
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        response.setContentType("application/json;charset=utf-8");
        //判断token是否存在
        if (StringUtils.isEmpty(token)){
            try {
                PrintWriter writer = response.getWriter();
                HashMap<String, Object> map = new HashMap<>();
                map.put("success",false);
                map.put("message","请登录");
                map.put("obj","noLogin");
                String s = JSONObject.toJSONString(map);
                writer.write(s);
                RequestContext.getCurrentContext().setSendZuulResponse(false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
